{% extends "base.html" %}

{% block content %}
<div class="bg-white rounded-lg shadow">
    <!-- 顶部操作栏 -->
    <div class="p-6 border-b border-gray-200">
        <div class="flex justify-between items-center">
            <div class="flex-1 max-w-sm">
                <div class="relative">
                    <input type="text" 
                           id="search"
                           class="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:border-blue-500"
                           placeholder="搜索环境名称或ID...">
                    <div class="absolute left-3 top-2.5">
                        <svg class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                        </svg>
                    </div>
                </div>
            </div>
            <button onclick="openAddModal()" 
                    class="ml-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none">
                新增环境
            </button>
        </div>
    </div>

    <!-- 表格 -->
    <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
            <thead>
                <tr>
                    <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        环境名称
                    </th>
                    <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        指纹浏览器标识
                    </th>
                    <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        创建时间
                    </th>
                    <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        状态
                    </th>
                    <th class="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        操作
                    </th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                {% for env in environments %}
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap">{{ env.name }}</td>
                    <td class="px-6 py-4 whitespace-nowrap">{{ env.browser_id }}</td>
                    <td class="px-6 py-4 whitespace-nowrap">{{ env.created_at.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" 
                                   class="sr-only peer"
                                   {% if env.status %}checked{% endif %}
                                   onchange="toggleStatus({{ env.id }}, this.checked)">
                            <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                        </label>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <button onclick="openEditModal({{ env.id }})"
                                class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                        <button onclick="confirmDelete({{ env.id }})"
                                class="text-red-600 hover:text-red-900">删除</button>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- 分页 -->
    <div class="px-6 py-4 border-t border-gray-200">
        <div class="flex items-center justify-between">
            <div class="text-sm text-gray-500">
                共 {{ total }} 条记录
            </div>
            <div class="flex space-x-2">
                {% if page > 1 %}
                <a href="?page={{ page-1 }}&size={{ size }}" 
                   class="px-3 py-1 border rounded hover:bg-gray-100">上一页</a>
                {% endif %}
                
                {% if page * size < total %}
                <a href="?page={{ page+1 }}&size={{ size }}"
                   class="px-3 py-1 border rounded hover:bg-gray-100">下一页</a>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑模态框 -->
<div id="environmentModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
            <h3 class="text-lg font-medium leading-6 text-gray-900" id="modalTitle">
                新增环境
            </h3>
            <form id="environmentForm" class="mt-4">
                <input type="hidden" id="envId">
                <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2">
                        环境名称
                    </label>
                    <input type="text" 
                           id="envName"
                           class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-blue-500"
                           required>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2">
                        指纹浏览器标识
                    </label>
                    <input type="text"
                           id="browserId"
                           class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-blue-500"
                           required>
                </div>
                <div class="mb-4">
                    <label class="block text-gray-700 text-sm font-bold mb-2">
                        备注
                    </label>
                    <textarea id="remarks"
                              class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:border-blue-500"
                              rows="3"></textarea>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button"
                            onclick="closeModal()"
                            class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 focus:outline-none">
                        取消
                    </button>
                    <button type="submit"
                            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none">
                        确定
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3 text-center">
            <h3 class="text-lg font-medium leading-6 text-gray-900">
                确认删除
            </h3>
            <div class="mt-2 px-7 py-3">
                <p class="text-gray-500">
                    确定要删除这个环境吗？此操作不可恢复。
                </p>
            </div>
            <div class="flex justify-center space-x-3 mt-4">
                <button onclick="closeDeleteModal()"
                        class="px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 focus:outline-none">
                    取消
                </button>
                <button onclick="deleteEnvironment()"
                        class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 focus:outline-none">
                    确认删除
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentDeleteId = null;

// 打开新增模态框
function openAddModal() {
    document.getElementById('modalTitle').textContent = '新增环境';
    document.getElementById('environmentForm').reset();
    document.getElementById('envId').value = '';
    document.getElementById('environmentModal').classList.remove('hidden');
}

// 打开编辑模态框
async function openEditModal(id) {
    document.getElementById('modalTitle').textContent = '编辑环境';
    document.getElementById('envId').value = id;
    
    try {
        const response = await fetch(`/environments/api/${id}`);
        const data = await response.json();
        
        document.getElementById('envName').value = data.name;
        document.getElementById('browserId').value = data.browser_id;
        document.getElementById('remarks').value = data.remarks || '';
        
        document.getElementById('environmentModal').classList.remove('hidden');
    } catch (error) {
        console.error('Error:', error);
        alert('获取环境信息失败');
    }
}

// 关闭模态框
function closeModal() {
    document.getElementById('environmentModal').classList.add('hidden');
}

// 打开删除确认框
function confirmDelete(id) {
    currentDeleteId = id;
    document.getElementById('deleteModal').classList.remove('hidden');
}

// 关闭删除确认框
function closeDeleteModal() {
    document.getElementById('deleteModal').classList.add('hidden');
    currentDeleteId = null;
}

// 切换状态
async function toggleStatus(id, status) {
    try {
        const response = await fetch(`/environments/api/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ status: status })
        });
        
        if (!response.ok) {
            throw new Error('更新状态失败');
        }
        
        // 可以添加一个成功提示
    } catch (error) {
        console.error('Error:', error);
        alert('更新状态失败');
    }
}

// 删除环境
async function deleteEnvironment() {
    if (!currentDeleteId) return;
    
    try {
        const response = await fetch(`/environments/api/${currentDeleteId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            throw new Error('删除失败');
        }
        
        // 刷新页面
        window.location.reload();
    } catch (error) {
        console.error('Error:', error);
        alert('删除失败');
    }
    
    closeDeleteModal();
}

// 表单提交
document.getElementById('environmentForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const id = document.getElementById('envId').value;
    const data = {
        name: document.getElementById('envName').value,
        browser_id: document.getElementById('browserId').value,
        remarks: document.getElementById('remarks').value
    };
    
    try {
        const response = await fetch(`/environments/api${id ? '/' + id : ''}`, {
            method: id ? 'PUT' : 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        if (!response.ok) {
            throw new Error(id ? '更新失败' : '创建失败');
        }
        
        // 刷新页面
        window.location.reload();
    } catch (error) {
        console.error('Error:', error);
        alert(error.message);
    }
});
</script>
{% endblock %} 